#include <iostream>
#include <thread>
#include <string>
#include <cstring>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

void handleReceive(int clientSocket) {
    char buffer[1024];
    while (true) {
        memset(buffer, 0, sizeof(buffer));
        int bytesReceived = recv(clientSocket, buffer, sizeof(buffer) - 1, 0);
        
        if (bytesReceived <= 0) {
            std::cout << "客户端已断开连接。" << std::endl;
            break;
        }
        
        std::cout << "客户端说: " << buffer << std::endl;
    }
    close(clientSocket);
}

void handleSend(int clientSocket) {
    std::string message;
    while (true) {
        std::getline(std::cin, message);
        if (send(clientSocket, message.c_str(), message.length(), 0) < 0) {
            std::cout << "连接已断开，无法发送消息。" << std::endl;
            break;
        }
    }
    close(clientSocket);
}

int main() {
    // 创建服务器套接字
    int serverSocket = socket(AF_INET, SOCK_STREAM, 0);
    if (serverSocket < 0) {
        std::cerr << "创建套接字失败" << std::endl;
        return 1;
    }
    
    // 设置端口复用选项
    int opt = 1;
    setsockopt(serverSocket, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
    
    // 绑定地址和端口
    struct sockaddr_in serverAddr;
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_addr.s_addr = INADDR_ANY;
    serverAddr.sin_port = htons(12345);
    
    if (bind(serverSocket, (struct sockaddr*)&serverAddr, sizeof(serverAddr)) < 0) {
        std::cerr << "绑定失败" << std::endl;
        close(serverSocket);
        return 1;
    }
    
    // 开始监听
    if (listen(serverSocket, 1) < 0) {
        std::cerr << "监听失败" << std::endl;
        close(serverSocket);
        return 1;
    }
    
    std::cout << "服务器已启动，等待客户端连接..." << std::endl;
    
    // 接受客户端连接
    struct sockaddr_in clientAddr;
    socklen_t clientAddrLen = sizeof(clientAddr);
    int clientSocket = accept(serverSocket, (struct sockaddr*)&clientAddr, &clientAddrLen);
    
    if (clientSocket < 0) {
        std::cerr << "接受连接失败" << std::endl;
        close(serverSocket);
        return 1;
    }
    
    std::cout << "客户端 " << inet_ntoa(clientAddr.sin_addr) << ":" 
              << ntohs(clientAddr.sin_port) << " 已连接。" << std::endl;
    
    // 创建收发线程
    std::thread receiveThread(handleReceive, clientSocket);
    std::thread sendThread(handleSend, clientSocket);
    
    // 等待线程结束
    receiveThread.join();
    sendThread.join();
    
    // 关闭服务器套接字
    close(serverSocket);
    std::cout << "服务器已关闭。" << std::endl;
    
    return 0;
}